package projectnfc.receiver.hro;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;

import android.R.color;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class WriteActivity extends Activity implements OnClickListener {
	private NfcAdapter mAdapter;
	private boolean mInWriteMode;
	private Button mWriteTagButton;
	private TextView mTextView;
	private EditText addStudentNummer;
	private String newStudentNummer;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.write);

		// Gets the default adapter
		mAdapter = NfcAdapter.getDefaultAdapter(this);

		// With this button we start the write function
		mWriteTagButton = (Button) findViewById(R.id.write_tag_button);
		mWriteTagButton.setOnClickListener(this);
		mWriteTagButton.setTextColor(Color.RED);

		// Textview used for output
		mTextView = (TextView) findViewById(R.id.text_view);
		mTextView.setTextColor(Color.RED);

		// Studentnummer / DocentCode
		addStudentNummer = (EditText) findViewById(R.id.addStudentNummer);
		addStudentNummer.setTextColor(Color.BLUE);
	}

	public void onClick(View v) {
		if (v.getId() == R.id.write_tag_button) {
			displayMessage("Houd de tag tegen de telefoon om te schrijven.");
			enableWriteMode();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		disableWriteMode();
	}

	// Called when our blank tag is scanned executing the PendingIntent
	@Override
	public void onNewIntent(Intent intent) {
		if (mInWriteMode) {
			mInWriteMode = false;

			// write to newly scanned tag
			Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
			writeTag(tag);
		}
	}

	// Force this Activity to get NFC events first
	private void enableWriteMode() {
		mInWriteMode = true;

		// set up a PendingIntent to open the app when a tag is scanned
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
				new Intent(this, getClass())
						.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
		IntentFilter tagDetected = new IntentFilter(
				NfcAdapter.ACTION_TAG_DISCOVERED);
		IntentFilter[] filters = new IntentFilter[] { tagDetected };

		mAdapter.enableForegroundDispatch(this, pendingIntent, filters, null);
	}

	private void disableWriteMode() {
		mAdapter.disableForegroundDispatch(this);
	}

	// Format a tag and write our NDEF message
	private boolean writeTag(Tag tag) {
		
		getStudentNummer();
		// Launch Playstore if app is not installed
		NdefRecord appRecord = NdefRecord
				.createApplicationRecord("projectnfc.receiver.hro");

		// record that contains the studentnummer
		byte[] payload = getStudentNr().getBytes();
		byte[] mBytes = MimeType.NFC.getBytes(Charset.forName("US-ASCII"));
		NdefRecord cardRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
				mBytes, new byte[0], payload);
		NdefMessage message = new NdefMessage(new NdefRecord[] { cardRecord,
				appRecord });

		try {
			// see if tag is already NDEF formatted
			Ndef ndef = Ndef.get(tag);
			if (ndef != null) {
				ndef.connect();

				if (!ndef.isWritable()) {
					displayMessage("Tag is niet schrijfbaar.");
					return false;
				}

				// work out how much space we need for the data
				int size = message.toByteArray().length;
				if (ndef.getMaxSize() < size) {
					displayMessage("Tag heeft niet voldoende ruimte.");
					return false;
				}

				ndef.writeNdefMessage(message);
				displayMessage("Tag succesvol geschreven!");
				return true;
			} else {
				// attempt to format tag
				NdefFormatable format = NdefFormatable.get(tag);
				if (format != null) {
					try {
						format.connect();
						format.format(message);
						displayMessage("Tag succesvol geschreven!\nScan een tag.");
						return true;
					} catch (IOException e) {
						displayMessage("Niet mogelijk om NDEF te formateren.");
						return false;
					}
				} else {
					displayMessage("Tag ondersteund geen NDEF format.");
					return false;
				}
			}
		} catch (Exception e) {
			displayMessage("Niet gelukt om te schrijven naar de tag.");
		}

		return false;
	}

	// Methods for set / get
	private void getStudentNummer() {
		newStudentNummer = addStudentNummer.getText().toString();
	}

	public String getStudentNr() {
		return addStudentNummer.getText().toString();
	}

	private void displayMessage(String message) {
		mTextView.setText(message);
	}
}